package com.sky.service.impl;

import com.sky.dto.OrderTop10DTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 统计指定时间区间内的营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合存储从begin到end的区间日期，包括begin和end，
        //如2024-12-20-2024-12-31     (2024-12-20 2024-12-21 2024-12-22.. 2024-12-31)
        List<LocalDate> dateList = getDate(begin, end);

        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            //查询时间从begin到end区间内订单的总金额,营业额指的是：订单状态为“已完成”的订单
            LocalDateTime dayBegin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime dayEnd = LocalDateTime.of(localDate, LocalTime.MAX);

            //select sum(amount) from orders where order_time > begin and order_time < end and status = 5
            Map map = new HashMap();
            map.put("begin",dayBegin);
            map.put("end",dayEnd);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.getAmountSumByTime(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }


    /**
     * 统计指定时间区间内的新增用户和用户总量列表
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDate(begin, end);

        //存放用户的总数量 select count(id) from user where create_time < end
        List<Integer> totalUserList = new ArrayList<>();
        //存放用户的新增数量 select count(id) from user where create_time > begin and create_time < end
        List<Integer> newUserList = new ArrayList<>();


        for (LocalDate date : dateList) {
            //当天开始时间
            LocalDateTime dayBegin = LocalDateTime.of(date,LocalTime.MIN);
            //当天结束时间
            LocalDateTime dayEnd = LocalDateTime.of(date,LocalTime.MAX);

            Map map = new HashMap();
            map.put("end",dayEnd);

            //用户总数量
            Integer totalUser = userMapper.countByMap(map);

            map.put("begin",dayBegin);

            //新增用户数量
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 统计指定时间区间内订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDate(begin, end);


        //存放每天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        //遍历dateList集合，查询每天有效的订单数和订单总数
        for (LocalDate date : dateList) {
            LocalDateTime dayBegin = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime dayEnd = LocalDateTime.of(date,LocalTime.MAX);
            //查询每天的订单总数 select count(id) from orders where order_time > day and order_time < day
            Integer orderCount = getOrderCount(dayBegin, dayEnd, null);

            //查询每天的有效订单数 select count(id) from orders where order_time > day and order_time < day and status = 5
            Integer validOrderCount = getOrderCount(dayBegin, dayEnd, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //计算时间区间内的订单有效总数量
        Integer totalValidOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = totalValidOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据条件统计订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.countByMap(map);
    }

    /**
     * 统计指定时间区间内的销量排名
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

        //SELECT od.`name`,od.number FROM `orders` o
        //left join order_detail od on o.id = od.order_id
        //where o.order_time > begin and o.order_time < end
        //order by od.number DESC LIMIT 0,10
        LocalDateTime dayBegin = LocalDateTime.of(begin,LocalTime.MIN);

        LocalDateTime endBegin = LocalDateTime.of(end,LocalTime.MAX);

        Map map = new HashMap();
        map.put("begin",dayBegin);
        map.put("end",endBegin);
        map.put("status",Orders.COMPLETED);
        List<OrderTop10DTO> details = orderMapper.getSaleTop10(map);

        //将查询的菜品或套餐名称和销售数量以stream流的形式展示，最后拼接成字符串
        List<String> name = details.stream().map(OrderTop10DTO::getName).collect(Collectors.toList());
        List<Integer> number = details.stream().map(OrderTop10DTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(name,","))
                .numberList(StringUtils.join(number,","))
                .build();
    }

    /**
     * 抽取区间所有日期方法
     * @param begin
     * @param end
     * @return
     */
    public List<LocalDate> getDate(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}